import { defineStore } from 'pinia';
import store from '@/store';
import { asyncRoutes } from '@/router';

// 判断是否有权限
function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some(role => {
			return route.meta.roles.includes(role);
		});
	} else {
		return true;
	}
}
// 递归获取有权限的路由
export function filterAsyncRoutes(routes, roles) {
	const res: any[] = [];
	routes.forEach(route => {
		const tmp = { ...route };
		if (hasPermission(roles, tmp)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, roles);
			}
			res.push(tmp);
		}
	});
	return res;
}

interface UserState {
	routes: any[];
}

export const usePermissionStore = defineStore('app-permission', {
	state: (): UserState => ({
		routes: [],
	}),
	getters: {},
	actions: {
		generateRoutes(roles) {
			return new Promise<any[]>(resolve => {
				const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
				this.routes = accessedRoutes;
				resolve(accessedRoutes);
			});
		},
	},
});

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
	return usePermissionStore(store);
}
